#!/usr/bin/env php
<?php
    //把目录指向当前运行文件目录
    $dir = dirname(__FILE__);
    chdir($dir);
    // chdir(dirname(dirname(__FILE__)));

    error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
    ignore_user_abort(1);
    set_time_limit(0);

    ///更新数据表
    if($argv[1] != 'dev'){
        echo $dir;
        echo "\n    **********     **********\n";
        echo "    *                       *\n";
        echo "    *                      *\n";
        echo "    **********            *\n";
        echo "    *                    *\n";
        echo "    *                   *\n";
        echo "    **********          *\n";
    }

    $dsn = require("../Config/compInfo.php");
    $dsn = $dsn['dbDSN'];

    // var_dump($dsn);
    $connection = mysql_connect($dsn['host'],$dsn['login'],$dsn['password']);
    if (!$connection) {
        die('Could not connect: ' . mysql_error());
    }

    //开始导入sql初始化数据
    mysql_select_db($dsn['database'], $connection);
    mysql_query("set names utf8");

    $sqlAll = actionGetPatchs4Up();

    foreach ($sqlAll as $f) {
        execute_file($f);
    }

    mysql_close($connection);
    if($sqlAll){
        echo ($_GET ? '<br/>' : " \n"),"+update database run finish";
    }else{
        echo ($_GET ? '<br/>' : " \n"),"----no sql need exec";
    }



    function actionGetPatchs4Up() {
        $patchPath = "../_Patchs/Files";
        //取得所有的补丁文件
        if ($dh = opendir($patchPath)) {
            while (false !== ($file = readdir($dh))) {
                //不是文件跳过
                if(!is_file($patchPath.'/'.$file)) continue;
                $temp = explode('_',$file);
                $temp1 = explode('.',$temp[2]);//将后缀名分割开

                //判断文件是否执行过
                $sql = "select * from sys_dbchange_log where fileName='{$file}'";
                $result = mysql_query($sql);
                $tmpRow = array();
                while($row = mysql_fetch_assoc($result))
                {
                    $tmpRow[] = $row;
                }

                if(count($tmpRow) > 0) continue;

                $arrFile[$temp[1].'_'.$temp1[0].'_'.$temp[0]] = $file;
            };

            closedir($dh);
        }
        //按创建时间排序
        ksort($arrFile);

        $arrNeed = array();
        foreach ($arrFile as $key=>&$v){
            if(in_array($v,$arrLog)) continue;
            $arrNeed[] = $v;
        }
        //dump($arrNeed);exit;
        return $arrNeed;
    }

    //导入sql文件
    function importSql($sql){
        // echo $sql,'<br/>','<br/>';
        if(trim($sql)){
            $sql = trim($sql).';';
            $q = mysql_query($sql);
            $error = mysql_error();
        }

        if($error){
            echo iconv("UTF-8" ,"GB2312", $sql." \n exec error :".$error),($_GET ? '<br/>' : " \n");
            return false;
        }

        return true;
    }

    //执行某个文件
    function execute_file($fileNameShot) {
        $patchPath = "../_Patchs/Files";
        //文件不存在返回错误
        $fileName = $patchPath.'/'.$fileNameShot;
        if(!file_exists($fileName)) {
            $arr = array('success'=>false,'msg'=>'文件不存在');
            return $arr;
        }


        //取得文件内容
        $content = file_get_contents($fileName);
        //去掉bom头
        $content = removeBOM($content);

        //作为sql语句执行,
        $arrSql = split(';',$content);
        foreach($arrSql as & $v) {
            $v = trim($v);
        }
        $arrSql = array_filter($arrSql);
        //如果sql语句执行错误，返回错误信息
        $error = array();
        foreach($arrSql as & $v) {
            $isSucc = importSql($v);
            if($isSucc == false){
                $error[] = $v;
            }
        }

        if($error){
            echo ($_GET ? '<br/>' : " \n") , '-',$fileName ,iconv("UTF-8" ,"GB2312", "执行失败 abort exec sql");
        }else{
            //如果sql语句执行成功,插入日志表中
            $content = mysql_real_escape_string($content);
            $sql = "INSERT into sys_dbchange_log (fileName,content) values ('{$fileNameShot}','{$content}');";
            // echo $sql;
            $res = mysql_query($sql);

            echo ($_GET ? '<br/>' : " \n") , '+',$fileName ,($res ? "[success]" : "[error]");
        }

    }

    function removeBOM($content) {
        $charset[1] = substr($content, 0, 1);
        $charset[2] = substr($content, 1, 1);
        $charset[3] = substr($content, 2, 1);
        if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
            $content = substr($content, 3);
        }
        return $content;
    }
